extends AudioStreamPlayer

# 音频设置
const SAMPLE_RATE: int = 16000
const CHUNK_SIZE: int = 1024
const BUFFER_LENGTH: float = 0.5  # 500ms缓冲区

# 播放状态
var _is_playing: bool = false
var _audio_queue: PackedVector2Array = PackedVector2Array()
var _audio_position: int = 0
var _last_push_time: float = 0.0  # 跟踪最后推送时间

# 生成器播放
var _generator_playback: AudioStreamGeneratorPlayback

func _ready():
	# 设置音频流生成器
	var generator = AudioStreamGenerator.new()
	generator.mix_rate = SAMPLE_RATE
	generator.buffer_length = BUFFER_LENGTH
	stream = generator
	
	# 连接全局信号
	if SherpaManager.tts_audio_received.is_connected(_on_tts_audio_received):
		SherpaManager.tts_audio_received.disconnect(_on_tts_audio_received)
	SherpaManager.tts_audio_received.connect(_on_tts_audio_received)
	
	print("TTS播放器初始化完成 | 采样率: %d Hz | 缓冲区: %.1f秒" % [SAMPLE_RATE, BUFFER_LENGTH])

func _on_tts_audio_received():
	var tts_audio = SherpaManager.get_tts_audio()
	if tts_audio.size() > 0:
		print("接收TTS音频数据: %d 样本 | 时长: %.2f秒" % [
			tts_audio.size(), 
			float(tts_audio.size()) / SAMPLE_RATE
		])
		_play_tts_audio(tts_audio)

func _play_tts_audio(audio_data: PackedFloat32Array):
	# 重置状态
	_reset_playback()
	
	# 转换为立体声
	_audio_queue = PackedVector2Array()
	_audio_queue.resize(audio_data.size())
	
	for i in range(audio_data.size()):
		_audio_queue[i] = Vector2(audio_data[i], audio_data[i])
	
	_audio_position = 0
	_last_push_time = Time.get_ticks_msec()
	
	# 确保生成器已准备就绪
	if !_generator_playback:
		play()
		_generator_playback = get_stream_playback()
		if !_generator_playback:
			push_error("无法获取AudioStreamGeneratorPlayback!")
			return
	
	# 清除现有缓冲区
	_generator_playback.clear_buffer()
	
	# 开始播放
	if !playing:
		play()
		print("启动音频播放器")
	
	_is_playing = true
	print("准备播放TTS音频: %d 帧 | 预计时长: %.2f秒" % [
		_audio_queue.size(), 
		float(_audio_queue.size()) / SAMPLE_RATE
	])

func _reset_playback():
	# 完全重置播放状态
	_is_playing = false
	_audio_queue = PackedVector2Array()
	_audio_position = 0
	
	if playing:
		stop()
		print("播放器已停止")

func _process(_delta):
	if !_is_playing || !playing:
		return
	
	# 获取可用帧数
	var available_frames = _generator_playback.get_frames_available()
	
	# 调试信息：显示缓冲区状态
	if Engine.get_frames_drawn() % 60 == 0:  # 每秒更新一次
		var buffer_fill = 1.0 - (float(available_frames) / (BUFFER_LENGTH * SAMPLE_RATE))
		print("缓冲区状态: %.1f%% 已填充 | 待推送: %d/%d" % [
			buffer_fill * 100,
			_audio_position,
			_audio_queue.size()
		])
	
	if available_frames <= 0:
		return
	
	# 计算需要推送的样本数
	var to_push = min(available_frames, _audio_queue.size() - _audio_position, CHUNK_SIZE)
	
	if to_push > 0:
		# 推送音频块
		var chunk = _audio_queue.slice(_audio_position, _audio_position + to_push)
		_generator_playback.push_buffer(chunk)
		_audio_position += to_push
		_last_push_time = Time.get_ticks_msec()
		
		# 每推送1秒数据打印一次进度
		if _audio_position % SAMPLE_RATE < CHUNK_SIZE:
			var progress = float(_audio_position) / _audio_queue.size() * 100
			var elapsed = float(_audio_position) / SAMPLE_RATE
			print("已推送: %.1f秒 | 进度: %.1f%%" % [elapsed, progress])
	
	# 检查播放是否完成
	if _audio_position >= _audio_queue.size():
		# 更可靠的完成检测：
		# 1. 所有数据已推送
		# 2. 超过预计播放时间
		# 3. 缓冲区几乎为空
		var expected_duration = float(_audio_queue.size()) / SAMPLE_RATE
		var time_since_last_push = (Time.get_ticks_msec() - _last_push_time) / 1000.0
		var buffer_fill_ratio = 1.0 - (float(available_frames) / (BUFFER_LENGTH * SAMPLE_RATE))
		
		if time_since_last_push > expected_duration || buffer_fill_ratio < 0.1:
			_finish_playback()

func _finish_playback():
	_is_playing = false
	stop()
	
	# 添加静音帧确保播放完成
	if _generator_playback:
		var available_frames = _generator_playback.get_frames_available()
		if available_frames > 0:
			var silence = PackedVector2Array()
			silence.resize(available_frames)
			for i in range(available_frames):
				silence[i] = Vector2.ZERO
			_generator_playback.push_buffer(silence)
	
	print("TTS音频播放完成")
	
	# 重置状态，准备下一次交互
	SherpaManager.state = SherpaManager.State.IDLE
	_reset_playback()
